﻿using System;
using System.Linq;
using System.Data.Linq;
using System.Collections.Generic;
using System.Text;
using HR.Appointments.DataLayer;

namespace HR.Appointments.Service.DataAccessLayer.DLinq
{
    internal class WorkstationDAO : IWorkstationDAO
    {
        #region IWorkstationDAO Members
        public List<WorkstationEntity> GetByCompany(int companyId)
        {
            var result = new List<WorkstationEntity>();
            using(DAODataContext ctx = new DAODataContext())
            {
                var sql = from data in ctx.Workstations
                          where data.CompanyId == companyId
                          select data;
                
                foreach(HR.Appointments.DataLayer.Workstation row in sql)
                {
                    result.Add(WorkstationEntity.Load(row));
                }
            }
            return result;
        }

        public WorkstationEntity GetInstance(int workstationId)
        {
            using (DAODataContext ctx = new DAODataContext())
            {
                var sql = from data in ctx.Workstations
                          where data.WorkstationId == workstationId
                          select data;

                return WorkstationEntity.Load(sql.FirstOrDefault());
            }
        }

        public void Insert(WorkstationEntity workstation)
        {
            using (DAODataContext ctx = new DAODataContext())
            {
                ctx.Workstations.InsertOnSubmit(workstation.ToData(null));
                ctx.SubmitChanges();
            }
        }

        public void Delete (int companyId, int workstationId)
		{
			using (DAODataContext ctx = new DAODataContext())
			{
				var sql = from data in ctx.Workstations
						  where data.CompanyId == companyId
						  && data.WorkstationId == workstationId
						  select data;

				if (sql.Count() != 0)
				{
					ctx.Workstations.DeleteOnSubmit(sql.FirstOrDefault());
					ctx.SubmitChanges();
				}
			}
		}

		public void Update(WorkstationEntity workstation)
		{
			using (DAODataContext ctx = new DAODataContext())
			{
				var sql = from data in ctx.Workstations
						  where data.WorkstationId == workstation.WorkstationId
						  select data;

				Workstation row = workstation.ToData(sql.FirstOrDefault());
				//ctx.Activities.InsertOnSubmit(activity.ToData(sql.FirstOrDefault()));
				ctx.SubmitChanges();
			}
        }
        #endregion
    }
}
